<?php

namespace App\Logic\Member\Form;

use App\Core\BaseListForm;
use App\Core\Exception\DefaultException;
use App\Model\Member\MemberModel;
use App\Model\Member\MemberProfitScoreModel;
use App\Model\Order\OrderModel;
use App\Model\UserModel;
use App\Util\CommonHelper;
use App\Util\UserIdentityHelper;
use EasySwoole\Mysqli\QueryBuilder;

class ProfitScoreListForm extends BaseListForm
{
    public $id;
    public $user_id;
    public $username;
    public $score;
    public $before_score;
    public $after_score;
    public $remark;
    public $type;
    public $object_id;
    public $referrer_profit_user_id;
    public $created_at;
    public $start_created_at;
    public $end_created_at;
    public $group;
    public $date;
    public $day;
    public $range;


    /**
     * 收益账户积分变动列表
     * @return \App\Core\Output
     * @throws DefaultException
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     */
    public function lists()
    {
        $where = [];
        if(UserIdentityHelper::getType() == UserModel::TYPE_INSIDE) {
            /**后台管理员*/
            if ($this->checkField($this->user_id)) {
                $where['user_id'] = $this->user_id;
            }
            if ($this->checkField($this->username)) {
                if(!$member = MemberModel::create()->getOne(['username' => $this->username])){
                    throw new DefaultException('用户不存在');
                }
                $where['user_id'] = $member->id;
            }
        }else{
            $this->user_id = UserIdentityHelper::getId();
            $where['user_id'] = $this->user_id;
        }

        if ($this->checkField($this->id)) {
            $where['id'] = $this->id;
        }
        if ($this->checkField($this->type)) {
            $where['type'] = $this->type;
        }

        if ($this->checkField($this->range)) {
            switch ($this->range){
                case 'day':
                    if (!$this->checkField($this->day) || strtotime($this->day) == 0) {
                        $this->day = date('Y-m-d');
                    }
                    $where['created_date'] = $this->day;
                    break;
                case 'week':
                    /**取出本周的开始和结束日期*/
                    $week_start_date = date('Y-m-d 00:00:00', strtotime('last monday'));
                    $week_end_date = date('Y-m-d 23:59:59', strtotime('next sunday'));
                    $where['created_at'] = [[$week_start_date, $week_end_date], 'between'];
                    break;
                case 'month':
                    /**取出本月的开始和结束日期*/
                    $month_start_date = date('Y-m-01 00:00:00');
                    $month_end_date = date('Y-m-d 23:59:59', strtotime(date('Y-m-01', strtotime('+1 month')))-1);
                    $where['created_at'] = [[$month_start_date, $month_end_date], 'between'];
                    break;
                case 'year':
                    /**取出本年的开始和结束日期*/
                    $year_start_date = date('Y-01-01 00:00:00');
                    $year_end_date = date('Y-12-31 23:59:59');
                    $where['created_at'] = [[$year_start_date, $year_end_date], 'between'];
                    break;
            }
        }
        if ($this->checkField($this->referrer_profit_user_id)) {
            $where['source_id'] = $this->referrer_profit_user_id;
            $where['type'] = MemberProfitScoreModel::TYPE_REFFERER_PROFIT;
        }
        if (!is_array($this->created_at) && $this->checkField($this->created_at) && strtotime($this->created_at) > 0) {
            $this->created_at = date('Y-m-d', strtotime($this->created_at));
            $where['created_at'] = [[$this->created_at . ' 00:00:00', $this->created_at . ' 23:59:59'], 'between'];
        }
        if ($this->checkField($this->date) && strtotime($this->date) > 0) {
            $firstDay = date('Y-m-01', strtotime($this->date)) . ' 00:00:00';
            $lastDay = date('Y-m-t', strtotime($this->date)). ' 23:59:59';
            $where['created_at'] = [[$firstDay, $lastDay ], 'between'];
        }
        if ($this->checkField($this->start_created_at) && $this->checkField($this->end_created_at)) {
            /**查询时间不能跨月*/
            $start_month = date('Y-m', strtotime($this->start_created_at));
            $end_month = date('Y-m', strtotime($this->end_created_at));
            if($start_month != $end_month) {
                throw new DefaultException('查询时间不能跨月');
            }
            $where['created_at'] = [[$this->start_created_at, $this->end_created_at], 'between'];
        }elseif ($this->checkField($this->start_created_at)) {
            $where['created_at'] = [$this->start_created_at, '>='];
        }elseif ($this->checkField($this->end_created_at)) {
            $where['created_at'] = [$this->end_created_at, '<='];
        }

        $model = MemberProfitScoreModel::makeQueryModel($where, [], $this->getPagination());

        $model->with(['member']);
        $model->order( 'id', 'DESC');

        $modelResult = $model->all();

        $list = [];
        foreach($modelResult as $v) {
            $item = [
                'id'                 => $v->id,
                'user_id'            => $v->user_id,
                'username'          => $v->member->username ?? '',
                'score'              => $v->score,
                'before_score'       => $v->before_score,
                'after_score'        => $v->after_score,
                'type'               => $v->type,
                'object_id'          => $v->object_id,
                'created_at'         => $v->created_at,
                'type_label'         => MemberProfitScoreModel::getTypeDict($v->type),
                'remark'             => $v->remark,
            ];
            $list[] = $item;
        }

        /**筛选出所有type=TYPE_REFFERER_PROFIT 的项目,取出object_id*/
        $reffererProfitList = array_filter($list, function($item) {
            return $item['type'] == MemberProfitScoreModel::TYPE_REFFERER_PROFIT;
        });
        $reffererProfitObjectIdList = array_column($reffererProfitList, 'object_id');

        /**如果$reffererProfitObjectIdList不为空,那么就通过id去获取订单信息*/
        if(!empty($reffererProfitObjectIdList)) {
            $reffererProfitObjectIdList = array_unique($reffererProfitObjectIdList);
            /**@see OrderModel::member() */
            $orderModel = OrderModel::makeQueryModel(['id' => [$reffererProfitObjectIdList, 'IN']]);
            $orderModel = $orderModel->tableName($orderModel::create()->getTableName());
            if ($reffererProfitOrders = $orderModel->with(['member'])->all()) {
                $orders = [];
                foreach ($reffererProfitOrders as $order) {
                    $item             = $order->toRawArray();
                    $item['username'] = $order->member->username;
                    $orders[]         = $item;
                }

                /**轮询reffererProfitOrders=>$order,如果$list中的object_id等于order中的id,那么将order.user_id赋值给$item['order_user_id']*/
                $list = array_map(function ($item) use ($orders) {
                    $order = array_filter($orders, function ($order) use ($item) {
                        return $order['id'] == $item['object_id'];
                    });
                    if (!empty($order)) {
                        $order                  = array_shift($order);
                        $item['order_user_id']  = $order['user_id'];
                        $item['order_username'] = $order['username'];
                        $item['order_id']       = $order['id'];
                    }
                    return $item;
                }, $list);
            }
        }

        if(!empty($this->group)) {
            $summarizedData = [];
            foreach ($list as $item) {
                $date                                 = date('Y-m-d', strtotime($item['created_at'])); // 提取日期部分
                $day                                  = date('Y年m月d日', strtotime($date)); // 格式化日期
                $summarizedData[$date]['item'][]      = $item;
                $summarizedData[$date]['day']         = $day;
                $summarizedData[$date]['total_score'] = isset($summarizedData[$date]['total_score']) ? bcadd($summarizedData[$date]['total_score'], $item['score'], 2) : $item['score'];
            }

            $list = array_values($summarizedData);
        }
        $total = $model->lastQueryResult()->getTotalCount();
        $pagination = $this->getPagination();
        $pagination['total_count'] = $total;

        $result = [
            'list'       => $list,
            'pagination' => $pagination
        ];
        return $result;
    }

}
